package com.scuec.groupfive.controller;
import com.scuec.groupfive.entity.StudyPlan;
import com.scuec.groupfive.service.StudyPlanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.Date;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;

@RestController
@RequestMapping("/api/study-plans")
@CrossOrigin(origins = {"http://localhost:5173", "http://localhost:5174"}, allowCredentials = "true")
public class StudyPlanController {

    private static final Logger logger = LoggerFactory.getLogger(StudyPlanController.class);

    @Autowired
    private StudyPlanService studyPlanService;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    @RequestMapping(method = RequestMethod.OPTIONS)
    public ResponseEntity<?> handleOptions() {
        return ResponseEntity.ok()
                .header("Access-Control-Allow-Origin", "http://localhost:5173")
                .header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
                .header("Access-Control-Allow-Headers", "*")
                .header("Access-Control-Allow-Credentials", "true")
                .header("Access-Control-Max-Age", "3600")
                .build();
    }

    // 简单的测试接口
    @GetMapping("/test")
    public ResponseEntity<?> testConnection(@RequestParam Long userId) {
        try {
            logger.info("Testing connection for userId: {}", userId);

            // 测试数据库连接
            String testSql = "SELECT COUNT(*) FROM study_plans";
            int totalCount = jdbcTemplate.queryForObject(testSql, Integer.class);
            logger.info("Total records in study_plans table: {}", totalCount);

            // 测试用户数据
            String userSql = "SELECT COUNT(*) FROM study_plans WHERE user_id = ?";
            int userCount = jdbcTemplate.queryForObject(userSql, Integer.class, userId);
            logger.info("Records for userId {}: {}", userId, userCount);

            // 测试表结构
            String structureSql = "DESCRIBE study_plans";
            List<Map<String, Object>> structure = jdbcTemplate.queryForList(structureSql);
            logger.info("Table structure: {}", structure);

            Map<String, Object> result = new HashMap<>();
            result.put("totalCount", totalCount);
            result.put("userCount", userCount);
            result.put("tableStructure", structure);
            result.put("message", "数据库连接正常");

            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("Error in test connection for userId: {}", userId, e);
            Map<String, Object> error = new HashMap<>();
            error.put("error", e.getMessage());
            error.put("stackTrace", e.getStackTrace());
            return ResponseEntity.status(500).body(error);
        }
    }

    @GetMapping("/today")
    public ResponseEntity<?> getTodayPlans(@RequestParam Long userId, HttpServletRequest request) {
        try {
            logger.info("Received request for today plans. Headers: {}", Collections.list(request.getHeaderNames()));
            logger.info("Getting today plans for userId: {}", userId);

            List<StudyPlan> plans = studyPlanService.findTodayPlans(userId);
            logger.info("Successfully retrieved {} plans for userId: {}", plans.size(), userId);
            return ResponseEntity.ok(plans);
        } catch (Exception e) {
            logger.error("Error getting today plans for userId: {}", userId, e);
            return ResponseEntity.status(500).body("获取今日计划失败: " + e.getMessage());
        }
    }

    @PostMapping("/create")
    public ResponseEntity<StudyPlan> addPlan(@RequestBody StudyPlan plan) {
        return ResponseEntity.ok(studyPlanService.addPlan(plan));
    }

    @PutMapping("/{taskId}")
    public ResponseEntity<StudyPlan> updatePlan(@PathVariable Long taskId, @RequestBody StudyPlan plan) {
        plan.setTaskId(taskId);
        return ResponseEntity.ok(studyPlanService.updatePlan(plan));
    }

    @DeleteMapping("/{taskId}")
    public ResponseEntity<Void> deletePlan(@PathVariable Long taskId, @RequestParam Long userId) {
        studyPlanService.deletePlan(taskId, userId);
        return ResponseEntity.ok().build();
    }

    @GetMapping("/history-unfinished")
    public ResponseEntity<?> getHistoryUnfinishedPlans(@RequestParam("userId") Long userId, HttpServletRequest request) {
        try {
            logger.info("Received request for history unfinished plans. Headers: {}", Collections.list(request.getHeaderNames()));
            logger.info("Getting history unfinished plans for userId: {}", userId);

            List<StudyPlan> plans = studyPlanService.findHistoryUnfinishedPlans(userId);
            logger.info("Successfully retrieved {} history unfinished plans for userId: {}", plans.size(), userId);
            return ResponseEntity.ok()
                    .header("Access-Control-Allow-Origin", "http://localhost:5173")
                    .header("Access-Control-Allow-Credentials", "true")
                    .body(plans);
        } catch (Exception e) {
            logger.error("Error getting history unfinished plans for userId: {}", userId, e);
            return ResponseEntity.status(500)
                    .header("Access-Control-Allow-Origin", "http://localhost:5173")
                    .header("Access-Control-Allow-Credentials", "true")
                    .body("获取历史未完成任务失败: " + e.getMessage());
        }
    }

    @GetMapping("/completed-days")
    public ResponseEntity<?> getCompletedDays(@RequestParam Long userId, @RequestParam String month) {
        try {
            logger.info("Getting completed days for userId: {} and month: {}", userId, month);
            List<String> days = studyPlanService.findCompletedDays(userId, month);
            logger.info("Successfully retrieved {} completed days for userId: {} and month: {}", days.size(), userId, month);
            return ResponseEntity.ok(days);
        } catch (Exception e) {
            logger.error("Error getting completed days for userId: {} and month: {}", userId, month, e);
            return ResponseEntity.status(500).body("获取完成日期失败: " + e.getMessage());
        }
    }
}